package com.ruoyi.web.controller.utils;

import com.ruoyi.common.utils.ConstantUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;


public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private  static  final  int SocketTimeout=800;
    private  static  final  int ConnectTimeout=800;
    private  static  final  int ConnectionRequestTimeout=800;

    public static Map doGetOkHttp(String url, Map<String, Object> params) throws RuntimeException {
        // 创建请求体
        Response response = null;
        try {
            final Request request = new Request.Builder()
                    .url(_getFullUrl(url, params))
                    .get()
                    .build();
            response = new OkHttpClient.Builder().build().newCall(request).execute();
            final String resultJson = response.body().string();
            return JsonUtils.jsonToPojo(resultJson, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * GET请求
     * @param url
     * @param params
     * @return
     * @throws RuntimeException
     */
    public static Map doGet(String url, Map<String, Object> params) throws RuntimeException {
        HttpGet get = new HttpGet(_getFullUrl(url, params));
        Map result = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse res = httpClient.execute(get);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String response = EntityUtils.toString(res.getEntity(), Charset.forName("UTF-8"));// 返回json格式
                result = JsonUtils.jsonToPojo(response, Map.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * GET请求
     * @param url
     * @return
     * @throws RuntimeException
     */
    public static Map doGetNew(String url) throws RuntimeException {
        HttpGet get = new HttpGet(url);
        Map result = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse res = httpClient.execute(get);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String response = EntityUtils.toString(res.getEntity(), Charset.forName("UTF-8"));// 返回json格式
                result = JsonUtils.jsonToPojo(response, Map.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }





    /**
     * POST请求
     * @param url
     * @param params
     * @return
     * @throws RuntimeException
     */
    public static String doPostReturnStr(String url, Map<String, Object> params) {
        HttpPost post = new HttpPost(url);
        try {
            if(params != null) {
                UrlEncodedFormEntity e = new UrlEncodedFormEntity(_getPostEntityParams(params), Charset.forName("UTF-8"));
                post.setEntity(e);
            }
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse res = httpClient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                return EntityUtils.toString(res.getEntity(), "utf-8");// 返回json格式
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //-------------------------------------------------------

    private static String _getFullUrl(String url, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder(url);
        if(params == null) {
            return sb.toString();
        }
        List<NameValuePair> nameValuePairList = Lists.newArrayList();
        Set<Map.Entry<String, Object>> set = params.entrySet();
        Iterator<Map.Entry<String, Object>> it = set.iterator();
        while(it.hasNext())
        {
            Map.Entry<String, Object> entry = it.next();
            if(entry.getValue() != null){
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        if(!nameValuePairList.isEmpty()) {
            try {
                String p = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, Consts.UTF_8));
                sb.append("?").append(p);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


    private static List<NameValuePair> _getPostEntityParams(Map<String, Object> params) {
        List<NameValuePair> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if(entry.getValue() != null)
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        return list;
    }


    //-------------------------------------------------------

    public static void main(String[] args) {
/*        Map resultMap  = null;
        //String ofOrderStatus = "";
       // resultMap = doOFPay("15622897242","D2022011911492310","30");
        //resultMap = doYHPay("15815521102","D2022011910142311","30");
        resultMap = getYHOrder("D2022011910142311");
        //ofOrderStatus = getOFOrderStatus("D2022011911492300");
        System.out.println("resultMap:"+JsonUtils.objectToJson(resultMap));*/
        System.out.println(UUID.randomUUID().toString());
        System.out.println(UUID.randomUUID().toString());
    }

    /**
     * 欧飞充值
     */
    private  static Map doOFPay(String gameUserId,String sporderId,String cardNum){
        String url = ConstantUtils.OUFEI_PAYURL;
        Map<String,Object> param = new HashMap<>();
        String userId = ConstantUtils.OUFEI_USER_ID;
        param.put("userid",userId);
        String userPws = MD5Util.toMD5(ConstantUtils.OUFEI_USER_PWD);
        param.put("userpws",userPws);
        String cardId = "140101";
        param.put("cardid",ConstantUtils.OUFEI_CARD_ID);
        param.put("cardnum",cardNum);
        //param.put("mctype","48"); //慢充需要传多少小时到账
        param.put("sporder_id",sporderId);
        String sporderTime = DateUtils.parseDateToStr("yyyyMMddHHmmss",new Date());
        param.put("sporder_time",sporderTime);
        param.put("game_userid",gameUserId); //18611142397 13671355890
        String userKey = ConstantUtils.OUFEI_KEY;

        StringBuffer sb = new StringBuffer();
        sb.append(userId).append(userPws).append(cardId).append(cardNum).append(sporderId).append(sporderTime).append(gameUserId).append(userKey);
        param.put("md5_str",MD5Util.toMD5(sb.toString()).toUpperCase());
        //param.put("ret_url",""); //回调地址（订单有状态了回调）
        param.put("version","6.0");
        String resultStr = doPostReturnStr(url,param);
        String jsonStr = JsonUtils.xml2JSON(resultStr);
        if(StringUtils.isNotEmpty(jsonStr)){
            return JsonUtils.jsonToPojo(jsonStr,Map.class);
        }else {
            return null;
        }
    }

    /**
     * 欧飞查订单状态
     * 返回的是状态，0充值中，1成功，9失败
     * @param sporderId
     * @return
     */
    private static String getOFOrderStatus(String sporderId){
        String url = ConstantUtils.OUFEI_ORDER_STATUS_URL;
        Map<String,Object> param = new HashMap<>();
        String userId = ConstantUtils.OUFEI_USER_ID;
        param.put("userid",userId);
        param.put("spbillid",sporderId);
        String resultStr = doPostReturnStr(url,param);
        return resultStr;
    }


    /**
     * 盈华充值
     */
    private static Map  doYHPay(String uid,String sporder,String price){
        String url = ConstantUtils.YINGHUA_PAYURL;
        Map<String,Object> param = new HashMap<>();
        String spid = ConstantUtils.YINGHUA_SPID;
        param.put("spid", spid);
        param.put("sporder",sporder);
        param.put("price",price);
        param.put("uid",uid); //18611142397 13671355890
        String ip = "121.8.131.82";
        param.put("ip",ip);  //112.94.10.109 、121.8.131.82、 14.23.157.66
        String payType = "3";
        param.put("paytype",payType);
        String smallcategories = "3";
        param.put("smallcategories",smallcategories);
        String timestamp = DateUtils.parseDateToStr("yyyyMMddHHmmss",new Date());
        param.put("timestamp",timestamp);
        String flowratetype = "0";
        param.put("flowratetype",flowratetype);
        StringBuffer sb = new StringBuffer();
        sb.append(spid).append(sporder).append(price).append(uid).append(ip).append(payType).append(flowratetype).append(ConstantUtils.YINGHUA_SECRET_KEY);
        String md5key =sb.toString();
        param.put("sign",MD5Util.toMD5(md5key));
        Map resultMap   = doGet(url,param);
        return resultMap;

    }



    /**
     * 获取盈华订单
     * 返回商户状态码（200：成功，202：充值中，   201：充值失败，203：参数错误，若状态码不在错误码列表内，请找人工核实订单
     */

    private static Map  getYHOrder(String sporder){
        String url = ConstantUtils.YINGHUA_ORDER_URL;
        Map<String,Object> param = new HashMap<>();
        String spid = ConstantUtils.YINGHUA_SPID;
        param.put("spid", spid);
        param.put("sporder",sporder);

        StringBuffer sb = new StringBuffer();
        sb.append(spid).append(sporder).append(ConstantUtils.YINGHUA_SECRET_KEY);
        String md5key =sb.toString();
        param.put("sign",MD5Util.toMD5(md5key));
        Map resultMap   = doGet(url,param);
        return resultMap;

    }



}
